package com.learn.authorization.pojo;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/04/07
 * @description 授权的变化就是需要添加permissions和authorities属性
 * getAuthorities()重写这个方法
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {
    private User user;
    private Set<String> permissions;
    @JSONField(serialize = false)
    private Set<GrantedAuthority> authorities;

    public LoginUser(User user, Set<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities == null) {
            authorities =
                    permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }
}
